//
//  ComposePictureController.swift
//  sinaDemo
//
//  Created by mac on 15/12/24.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit

private let maxPictureCount = 9
private let imageViewMargin: CGFloat = 8
private let maxColums: CGFloat = 3

private let reuseIdentifier = "Cell"

class ComposePictureController: UICollectionViewController {
    
    // 定义外部属性
    var images = [UIImage]()
    
    init() {
        let flowlayout = UICollectionViewFlowLayout()
        let itemWH: CGFloat = (screenBoundsWidth - (maxColums + 1) * imageViewMargin) / maxColums
        // 设置item的尺寸属性
        flowlayout.minimumInteritemSpacing = imageViewMargin
        flowlayout.minimumLineSpacing = imageViewMargin
        flowlayout.sectionInset = UIEdgeInsets(top: imageViewMargin, left: imageViewMargin, bottom: 0, right: imageViewMargin)
        flowlayout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        super.init(collectionViewLayout: flowlayout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置背景颜色
        collectionView?.backgroundColor = UIColor.blackColor()
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(composePictureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 如果图片的数量已经等于最大的图片数量,那么就设置总数量为0
        let delta = images.count == maxPictureCount ? 0 : 1
        return images.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! composePictureCell
        // 因为当没有图片的时候,数组是空的,但是item是可以取到0的
        if images.count == indexPath.item { // 只有刚开始的时候是相等的
            cell.image = nil
        }else {
            cell.image = images[indexPath.item]
        }
        cell.delegate = self
//        cell.backgroundColor = UIColor.randomColor()
    
        return cell
    }

}

// MARK: composePictureCellDelegate
extension ComposePictureController: composePictureCellDelegate {
    // 添加按钮
    func composePictureCellDidClickAddButton(cell: composePictureCell) {
        if cell.image != nil { // 已经有图片了,直接返回
            return
        }
        // modal出照片选择器
        let pictureVC = UIImagePickerController()
        pictureVC.delegate = self
        presentViewController(pictureVC, animated: true, completion: nil)
    }
    
    // 删除按钮
    func composePictureCellDidClickDeleteButton(cell: composePictureCell) {
        // 把点击cell的位置的图片给删除,然后刷新表格
        let indexPath = collectionView?.indexPathForCell(cell)
        images.removeAtIndex((indexPath?.item)!)
        collectionView?.reloadData()
    }
}

// MARK: UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension ComposePictureController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 选中照片以后,把图片加到图片数组里,并且刷新表格
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        images.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

// 代理方法
@objc protocol composePictureCellDelegate: NSObjectProtocol {
    // 添加按钮
    optional func composePictureCellDidClickAddButton(cell: composePictureCell)
    
    // 删除按钮
    optional func composePictureCellDidClickDeleteButton(cell: composePictureCell)
}

class composePictureCell: UICollectionViewCell {
    
    // 定义外部属性
    var image: UIImage? {
        didSet {
            // 如果有图片的话,那么就隐藏删除按钮
            deleteButton.hidden = image == nil
            addButton.setImage(image, forState: UIControlState.Normal)
        }
    }
    
    // 按钮的点击事件
    @objc private func clickAddButton(cell: composePictureCell) {
        print(__FUNCTION__)
        // 代理是可选项,所以是?, 代理方法是可选方法,所以也是?
        delegate?.composePictureCellDidClickAddButton?(self)
    }
    
    @objc private func clickDeleteButton(cell: composePictureCell) {
        print(__FUNCTION__)
        delegate?.composePictureCellDidClickDeleteButton?(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 初始化子控件
        setUpUI()
    }
    
    // 初始化子控件
    private func setUpUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        // 添加按钮的点击事件
        addButton.addTarget(self, action: "clickAddButton:", forControlEvents: UIControlEvents.TouchUpInside)
        deleteButton.addTarget(self, action: "clickDeleteButton:", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置约束
        addButton.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        // 修改按钮内部iamgeview的显示模式
        addButton.imageView?.contentMode = .ScaleAspectFill
        
    }
    
    // MARK: 懒加载
    // 添加按钮
    private lazy var addButton: UIButton = UIButton(image: nil, backImage: "compose_pic_add")
    
    // 删除按钮
    private lazy var deleteButton: UIButton = UIButton(image: nil, backImage: "compose_photo_close")
    
    // 代理属性,是可选项,因为代理可以没有值
    weak var delegate: composePictureCellDelegate?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
